package com.zjj.lbw.interview.funmath;

/**
 * @author zhanglei.zjj
 * @description 求x平方根的整数部分-基于二分查找|牛顿迭代
 * @date 2023/9/1 0:29
 */
public class Sqrt {
    public static int binarySearch(int x) {
        int left = 0, right = x;
        // 如果找不到返回 -1，但是这个题目场景一定会找到
        int index = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (mid * mid <= x) {
                index = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return index;

    }

    public static int newton(int x) {
        if (x <= 0) {
            return -1;
        }
        return recursion(x, x);
    }
    private static int recursion(double n, int x) {
        double mid = (x / n + n) / 2;
        if (mid == n) {
            return (int) mid;
        } else {
            return recursion(mid, x);
        }
    }

    public static void main(String[] args) {
        int i = binarySearch(24);
//        int i = newton(24);
        System.out.println(i);
    }
}
